package com.agilya.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.agilya.modele.QCM;

/**
 * Servlet implementation class AfficherCorrection
 * 
 * Permet d'afficher question par question la correction ainsi que la note d'un QCM réalisé
 * 
 */
@WebServlet("/AfficherCorrection")
public class AfficherCorrection extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AfficherCorrection() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		// cas du retour arrière
		if (request.getParameter("action") != null && request.getParameter("action").equals("retour")) {
			// On récupère la question courante
			int questionPrecedente = Integer.parseInt(request.getParameter("questionCourante")) - 1;
			request.setAttribute("questionCourante", questionPrecedente);
		} else {
			request.setAttribute("questionCourante", 1);
		}

		request.setAttribute("page", "/afficherCorrection.jsp");
		RequestDispatcher rd = request.getRequestDispatcher("/page.jsp");
		rd.forward(request, response);

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		RequestDispatcher rd = request.getRequestDispatcher("/page.jsp");
		request.setAttribute("page", "/afficherCorrection.jsp");

		QCM qcm = null;
		// récupération du QCM en session
		try {
			qcm = (QCM) session.getAttribute("qcm");

			// numéro de la question en cours
			int questionCourante = Integer.parseInt(request.getParameter("questionCourante"));

			// on teste si on est dans la dernière question
			if (questionCourante < qcm.getListeQuestions().size()) {

				request.setAttribute("questionCourante", questionCourante + 1);

				request.setAttribute("page", "/afficherCorrection.jsp");

				rd = request.getRequestDispatcher("/page.jsp");
			} else {
				rd = request.getRequestDispatcher("/AfficherResultat");
			}
		} catch (NullPointerException e) {
			// Le qcm n'est plus en session
			// Le message d'erreur sera affiché par la jsp
			request.setAttribute("page", "/afficherCorrection.jsp");
		}
		rd.forward(request, response);

	}
}
